package com.h2cloud.file;

/**
 * @Package: com.h2cloud.file
 * @ClassName: FileWatcherWithContent
 * @Author: h2cloud
 * @CreateTime: 2023/4/3 9:58 下午
 * @Description:
 */

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

public class FileWatcherWithContent {
	public static void main(String[] args) throws Exception {
		Path directory = Paths.get("/Users/h2cloud/javaproject/javaStudy/src/main/java/com/h2cloud/file"); // 监控的目录路径
		registerAll(directory);

		while (true) {
			WatchKey key = watchService.take(); // 阻塞等待事件
			for (WatchEvent<?> event : key.pollEvents()) {
				WatchEvent.Kind<?> kind = event.kind();
				if (kind == StandardWatchEventKinds.ENTRY_CREATE ||
						kind == StandardWatchEventKinds.ENTRY_MODIFY ||
						kind == StandardWatchEventKinds.ENTRY_DELETE) {
					Path modifiedFile = (Path) event.context();
					Path file = ((Path) key.watchable()).resolve(modifiedFile);

					String eventType = kind.name().substring("ENTRY_".length());
					System.out.println("File " + file + " has been " + eventType.toLowerCase() + ":");

					if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
						try {
							List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
							String content = String.join(System.lineSeparator(), lines);
							System.out.println(content);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
			key.reset();
		}
	}

	private static WatchService watchService;

	private static void registerAll(Path path) throws IOException {
		// 注册当前目录
		path.register(watchService,
				StandardWatchEventKinds.ENTRY_CREATE,
				StandardWatchEventKinds.ENTRY_MODIFY,
				StandardWatchEventKinds.ENTRY_DELETE);

		// 递归注册子目录
		Files.list(path)
				.filter(Files::isDirectory)
				.forEach(dir -> {
					try {
						registerAll(dir);
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
	}

	static {
		try {
			watchService = FileSystems.getDefault().newWatchService();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

